<template>
    <div class="main coupon-edit">
        <section>
            <el-form :model="formData" :rules="formRules" :disabled="type==='view'" size="medium" ref="form" label-width="150px">
                <div class="block-header"><div>基础信息</div></div>
                <div class="block-content">
                    <el-form-item label="优惠券名称:" prop="name" :rules="commonRules.notNullRule">
                        <el-input v-model="formData.name" placeholder="优惠券名称,最多10个字" maxLength="10"></el-input>
                    </el-form-item>
                    <el-form-item label="使用说明:" prop="rule">
                        <el-input type="textarea" v-model="formData.rule" :rows="3" resize="none" placeholder="庆国庆优惠券 使用时间：2019-10-01 00:00:00 - 2019-10-07 23:59:59 优惠券内容：部分商品，满100元减10元优惠券，最多50个字" maxLength="50"></el-input>
                    </el-form-item>
                    <el-form-item label="跳转类型:" prop="rule">
                        <el-radio v-for="(value, key) in linkTypeData" v-model="formData.linkType" :key="key" :label="key">{{value}}</el-radio>
                    </el-form-item>
                    <el-form-item label="跳转URL:" prop="link" :rules="commonRules.ignoreInvite" v-if="formData.linkType === 'URL'">
                        <el-input v-model="formData.link" placeholder="跳转URL"></el-input>
                    </el-form-item>
                    <template v-if="formData.linkType === 'IN_PAGE'">
                        <el-form-item label="内页类型:" prop="type">
                            <el-radio v-for="(item, index) in pageTypes" v-model="formData.inpageType" :label="item.val" :key="index" @change="changeType">{{item.name}}</el-radio>
                        </el-form-item>
                        <el-form-item :label="`跳转:`" prop="jumpId">
                            <span v-text="formData.inpageName||formData.inpageValue"></span>
                            <el-button type="primary" plain @click="chooseJump">请选择</el-button>
                        </el-form-item>
                    </template>
                </div>

                <div class="block-header"><div>使用规则</div></div>
                <div class="block-content">
                    <el-form-item label="使用门槛:" :prop="formData.useStandard==='LIMITED'?'standardPrice':'useStandard'" :rules="formData.useStandard==='LIMITED'?commonRules.priceRule:commonRules.notNullRule">
                        <el-radio :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="formData.useStandard" label="LIMITED" @change="changeValidate"><span></span></el-radio>
                        <template>
                            满 <el-input type="number" :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model.number="formData.standardPrice" placeholder="请输入" style="width: 130px;"></el-input> 元可使用（不包含运费）
                        </template>
                        <br/>
                        <el-radio :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="formData.useStandard" label="UNLIMITED" @change="changeValidate">无门槛</el-radio>
                    </el-form-item>
                    <el-form-item label="优惠形式:" :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" prop="price" :rules="commonRules.priceRule">
                        <el-radio :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="formData.couponType" label="COMMON" @change="changeValidate">抵扣券</el-radio>
                        <template v-if="formData.couponType==='COMMON'">
                            &nbsp;&nbsp;&nbsp;&nbsp;抵扣金额 <el-input type="number" :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model.number="formData.price" placeholder="请输入" style="width: 130px;"></el-input> 元
                        </template>
                        <br/>
                        <!--<el-radio v-model="formData.couponType" label="DISCOUNT" @change="changeValidate">折扣券</el-radio>-->
                    </el-form-item>
                    <el-form-item label="领券方式:" :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" prop="receiveType" :rules="commonRules.notNullRule">
                        <el-radio  :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="formData.receiveType" :label="1">自主领取</el-radio>
                        <el-radio  :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="formData.receiveType" :label="2">系统发放</el-radio>
                    </el-form-item>
                    <el-form-item label="限定范围:" :prop="formData.useType==='BY_CONDITION'?'relationList':'useType'" >
                        <el-radio :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="formData.useType" label="BY_NONE" @change="changeValidate">不限制</el-radio><br/>
                        <el-radio :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="formData.useType" label="BY_CONDITION" @change="changeValidate">指定</el-radio>
                        <template v-if="formData.useType==='BY_CONDITION'">
                            <div class="use-type-block">
                              <!-- <span>用户类型：</span> -->
                              <el-checkbox v-model="formData['BY_USER_GROUP']" :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'">用户类型：</el-checkbox>
                              <el-checkbox-group :disabled="!formData['BY_USER_GROUP'] || formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="userGroup" @change="setUserGroup">
                                <el-checkbox label="NewUser" key="NewUser">新人用户</el-checkbox>
                              </el-checkbox-group>
                            </div>
                            <div class="use-type-block">
                                <!-- <span>用户等级：</span> -->
                                <el-checkbox v-model="formData['BY_USER_TYPE']" :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'">用户等级：</el-checkbox>
                                <el-checkbox-group :disabled="!formData['BY_USER_TYPE'] || formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="tempUserLevels" @change="setUserLevels">
                                    <el-checkbox label="0" :key="0">普通会员</el-checkbox>
                                    <el-checkbox label="1" :key="1">VIP会员</el-checkbox>
                                    <el-checkbox label="2" :key="2">钻石会员</el-checkbox>
                                    <el-checkbox label="3" :key="3">董事会员</el-checkbox>
                                </el-checkbox-group>
                            </div>
                            <div class="use-type-block">
                                <el-checkbox v-model="formData['BY_MODEL_TYPE']" :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED' || useGoodsType === 'by_goods'">商品模式：</el-checkbox>
                                <el-checkbox-group :disabled="!formData['BY_MODEL_TYPE'] || formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="tempGoodsModel" @change="setGoodsModel">
                                    <el-checkbox label="1" :key="1">自营</el-checkbox>
                                    <el-checkbox label="2" :key="2">招商</el-checkbox>
                                </el-checkbox-group>
                            </div>
                            <div class="use-type-block">
                                <el-checkbox v-model="formData['BY_GOODS_TYPE']" :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED' || useGoodsType === 'by_goods'" >商品分类：</el-checkbox>
                                <el-tree
                                        :data="goodsCategory"
                                        show-checkbox
                                        check-on-click-node
                                        accordion
                                        node-key="id"
                                        ref="tree"
                                        highlight-current
                                        :props="{ children: 'children', label: 'name', disabled: ()=>{return (!formData['BY_GOODS_TYPE'] || formData.activeState==='ACTIVITY_STATE_STOPPED')} }"
                                        :default-checked-keys="tempGoodsCategory"
                                        @check="setGoodsCategory">
                                </el-tree>
                            </div>
                            <div class="use-type-block" style="margin-top: 10px;">
                                <el-checkbox v-model="formData['BY_GOODS']"  :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED' || useGoodsType === 'by_goods_type'">指定商品：</el-checkbox>
                                <el-button :disabled="!formData['BY_GOODS'] || formData.activeState==='ACTIVITY_STATE_STOPPED'" type="primary" icon="el-icon-plus" size="small" @click="chooseGoods" plain>添加商品</el-button>
                            </div>
                            <div class="use-type-block">
                              <div class="good-list" style="margin-top: 10px;">
                                <el-table :data="tempGoodsSelect" border highlight-current-row>
                                  <el-table-column align="center" width="60" label="序号" type="index"></el-table-column>
                                  <el-table-column align="center" width="300" label="ID" prop="goods_id"></el-table-column>
                                  <el-table-column align="center" width="300" label="名称" prop="title"></el-table-column>
                                  <el-table-column align="center" label="操作" width="100">
                                      <template slot-scope="scope">
                                          <el-button :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" type="danger" size="mini" @click="removeTempSelect(scope.row)">移除</el-button>
                                      </template>
                                  </el-table-column>
                                </el-table>
                              </div>
                            </div>
                            <div class="use-type-block" style="margin-top: 10px;">
                                <el-checkbox v-model="formData['BY_PACKAGE']"  :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED' || useGoodsType === 'by_goods_type'" >指定套餐：</el-checkbox>
                                <el-button :disabled="!formData['BY_PACKAGE'] || formData.activeState==='ACTIVITY_STATE_STOPPED'" type="success" icon="el-icon-plus" size="small" @click="chooseGoodsPackage" plain>添加套餐</el-button>
                            </div>
                            <div class="use-type-block">
                              <div class="good-list" style="margin-top: 10px;">
                                <el-table :data="tempPackageSelect" border highlight-current-row>
                                  <el-table-column align="center" width="60" label="序号" type="index"></el-table-column>
                                  <el-table-column align="center" width="300" label="ID" prop="goods_id"></el-table-column>
                                  <el-table-column align="center" width="300" label="名称" prop="title"></el-table-column>
                                  <el-table-column align="center" label="操作" width="100">
                                      <template slot-scope="scope">
                                          <el-button :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" type="danger" size="mini" @click="removeTempPackageSelect(scope.row)">移除</el-button>
                                      </template>
                                  </el-table-column>
                                </el-table>
                              </div>
                            </div>
                        </template>
                    </el-form-item>
                    <el-form-item label="商品黑名单设置:">
                        <template>
                            <div class="use-type-block">
                              <el-checkbox v-model="formData['BY_GOODS_BLACK']" :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'">指定商品不参加：</el-checkbox>
                              <el-button :disabled="!formData['BY_GOODS_BLACK']" type="primary" icon="el-icon-plus" size="small" @click="chooseGoodsBlack" plain>添加商品</el-button>
                            </div>
                            <div class="use-type-block">
                              <div class="good-list" style="margin-top: 10px;">
                                <el-table :data="tempGoodsSelectBlack" border highlight-current-row>
                                  <el-table-column align="center" width="60" label="序号" type="index"></el-table-column>
                                  <el-table-column align="center" width="300" label="ID" prop="foreignUuid"></el-table-column>
                                  <el-table-column align="center" width="300" label="名称" prop="foreignName"></el-table-column>
                                  <el-table-column align="center" label="操作" width="100">
                                      <template slot-scope="scope">
                                          <el-button :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" type="danger" size="mini" @click="removeTempSelectBlack(scope.row)">移除</el-button>
                                      </template>
                                  </el-table-column>
                                </el-table>
                              </div>
                            </div>
                            <div class="use-type-block" style="margin-top: 10px;">
                                <el-checkbox v-model="formData['BY_PACKAGE_BLACK']" :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'">指定套餐不参加：</el-checkbox>
                                <el-button :disabled="!formData['BY_PACKAGE_BLACK']" type="success" icon="el-icon-plus" size="small" @click="chooseGoodsPackageBlack" plain>添加套餐</el-button>
                            </div>
                            <div class="use-type-block">
                              <div class="good-list" style="margin-top: 10px;">
                                <el-table :data="tempPackageSelectBlack" border highlight-current-row>
                                  <el-table-column align="center" width="60" label="序号" type="index"></el-table-column>
                                  <el-table-column align="center" width="300" label="ID" prop="foreignUuid"></el-table-column>
                                  <el-table-column align="center" width="300" label="名称" prop="foreignName"></el-table-column>
                                  <el-table-column align="center" label="操作" width="100">
                                      <template slot-scope="scope">
                                          <el-button :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" type="danger" size="mini" @click="removeTempPackageSelectBlack(scope.row)">移除</el-button>
                                      </template>
                                  </el-table-column>
                                </el-table>
                              </div>
                            </div>
                        </template>
                    </el-form-item>
                    <el-form-item label="领取时间:" prop="receiveTimeRange" :rules="commonRules.notNullRule">
                        <el-date-picker
                                :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'"
                                style="width: 500px"
                                v-model="formData.receiveTimeRange"
                                type="datetimerange"
                                range-separator="~"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                value-format="yyyy-MM-dd HH:mm:ss">
                                <!-- format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd hh:mm:ss"> -->
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="使用有效期:" :prop="formData.useTimeType==='BY_DAYS'?'useDays':'useTimeRange'" :rules="formData.useTimeType==='BY_DAYS'?commonRules.numberRule:commonRules.notNullRule">
                        <el-radio :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="formData.useTimeType" label="BY_DAYS" @change="changeValidate">领券当日起</el-radio>
                        <template v-if="formData.useTimeType==='BY_DAYS'">
                            &nbsp;&nbsp;&nbsp;&nbsp; <el-input :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="formData.useDays" placeholder="请输入" style="width: 100px;"></el-input> 天可使用
                        </template>
                        <br/>
                        <el-radio :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="formData.useTimeType" label="BY_BETWEEN" @change="changeValidate">有效日期</el-radio>
                        <template v-if="formData.useTimeType==='BY_BETWEEN'">
                            &nbsp;&nbsp;&nbsp;&nbsp;
                            <el-date-picker
                                    :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'"
                                    style="width: 500px"
                                    v-model="formData.useTimeRange"
                                    type="datetimerange"
                                    range-separator="~"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </template>
                    </el-form-item>
                </div>
                <div class="block-header"><div>发券规则</div></div>
                <div class="block-content">
                    <el-form-item label="发券总量:" :prop="formData.quantityType==='LIMITED'?'quantity':'quantityType'" :rules="formData.quantityType==='LIMITED'?commonRules.numberRule:commonRules.notNullSelectRule">
                        <el-radio v-model="formData.quantityType" label="LIMITED" @change="changeValidate">限制</el-radio>
                        <template v-if="formData.quantityType==='LIMITED'">
                            &nbsp;&nbsp;&nbsp;&nbsp;<el-input type="number" v-model="formData.quantity" placeholder="请输入" oninput="if(value.length>8)value=value.slice(0,8)" style="width: 140px;"></el-input> 张<span class="adviceTxt">（1.达到限制数量时不再发券；2.修改优惠券总量时只能增加不能减少，请谨慎设置）</span>
                        </template>
                        <br/>
                        <el-radio v-model="formData.quantityType" label="UNLIMITED" @change="changeValidate">不限制</el-radio>
                    </el-form-item>
                    <el-form-item label="领券设置:" prop="repeatReceive">
                        <el-radio v-model="formData.repeatReceive" :label="1">只能领一次</el-radio>
                        <el-radio v-model="formData.repeatReceive" :label="2">每日限领取</el-radio>
                        <el-radio v-model="formData.repeatReceive" :label="0">可重复领取</el-radio>
                        <template v-if="formData.repeatReceive=='0' || formData.repeatReceive=='2'">
                            &nbsp;&nbsp;&nbsp;&nbsp;<el-input type="number" v-model="formData.repeatQuantity" placeholder="请输入" oninput="if(value<0)value=0" style="width: 140px;"></el-input> 次<span class="adviceTxt">（可重复领取次数, 0为不限制）</span>
                        </template>
                    </el-form-item>
                    <el-form-item label="状态:" prop="enabled">
                        <el-radio v-model="formData.enabled" :label="1">开启</el-radio>
                        <el-radio v-model="formData.enabled" :label="0">停止</el-radio>
                        <span class="adviceTxt">（停止后任何途径无法领取，已领取的券仍可继续使用）</span>
                    </el-form-item>
                    <el-form-item label="" v-if="type!=='view'">
                        <el-button type="primary" size="medium" :loading="btnLoading" @click="save">保存</el-button>
                        <el-button type="info" size="medium" plain @click="$router.push({ name: 'activityCoupon' })">取消</el-button>
                    </el-form-item>
                </div>
            </el-form>

            <div v-if="type==='view'" style="margin-left: 150px">
                <el-button type="success" size="medium" @click="$router.push({ name: 'activityCoupon' })">返回</el-button>
            </div>
        </section>
    </div>
</template>
<script>
  export default {
    name: 'couponEdit',
    props: {
      id: { default: '' },
      type: { default: 'edit' }
    },
    data(){
      return {
        linkTypeData: {
          'NONE': '无',
          'URL': 'URL',
          'IN_PAGE': '内页'
        },
        jumpTypes: [
            { name: '无', val: 1},
            { name: 'URL', val: 2},
            { name: '内页', val: 3}
        ],    // 跳转类型
        pageTypes: [
            { name: '商品', val: 'GOODS'},
            { name: '套餐', val: 'PACKAGE'}
        ],    // 内页类型
        // 会员等级
        userLevels: ['普通用户', '兰蜜', '大区', '董事'],
        // 模式
        businessModel: ['', '自营', '招商'],
        // 商品分类
        goodsCategory: [],

        userGroup: [],
        tempUserLevels: [],
        tempGoodsModel: [],
        tempGoodsCategory: [],
        tempGoodsSelect: [],
        tempPackageSelect: [],
        tempGoodsSelectBlack: [],
        tempPackageSelectBlack: [],
        setGoodsCategoryTemp: [],
        pageLoading: false,
        btnLoading: false,
        formData: {
          activeState: '',
          name: '',
          rule: '',
          linkType: 'NONE',
          link: '',
          useStandard: 'LIMITED',
          standardPrice: '',
          couponType: 'COMMON',
          price: '',
          useType: 'BY_CONDITION',
          relationList: [],
          receiveTimeRange: [],
          receiveStartTime: '',
          receiveStopTime: '',
          useTimeType: 'BY_DAYS',
          useDays: '',
          useTimeRange: [],
          useStartTime: '',
          useStopTime: '',
          quantityType: 'LIMITED',
          quantity: '',
          receiveType: 1,
          repeatReceive: 1,
          repeatQuantity: 1,
          enabled: 0,
          goodsBlackList: [],
          packageBlackList: []
        },
        formRules: {}
      }
    },
    created(){
      this.fetchData();
      this.fetchCategoryData();
    },
    watch: {
      $route() {
        this.fetchData()
      }
    },
    computed: {
      useGoodsType() {
        if(this.formData['BY_MODEL_TYPE'] || this.formData['BY_GOODS_TYPE']) {
          return 'by_goods_type'
        }
        if(this.formData['BY_GOODS'] || this.formData['BY_PACKAGE']) {
          return 'by_goods'
        }
        return ''
      }
    },
    methods: {
      fetchData(){
        if(this.id){
          this.pageLoading = true;
          this.request({
            url: '/coupon/system/activity/get',
            method: 'post',
            data: { couponActivityId: this.id }
          }).then(({data}) => {
            this.formData = {
              ...data,
              receiveTimeRange: data.receiveStartTime ? [data.receiveStartTime, data.receiveStopTime]:[],
              useTimeRange: data.useStartTime ? [data.useStartTime, data.useStopTime]:[]
            };
            this.userGroup = data.relationList.filter(item => item.useType ==='BY_USER_GROUP').map(item => item.relationId);
            this.tempUserLevels = data.relationList.filter(item => item.useType ==='BY_USER_TYPE').map(item => item.relationId);
            this.tempGoodsModel = data.relationList.filter(item => item.useType ==='BY_MODEL_TYPE').map(item => item.relationId);
            this.tempGoodsCategory = data.relationList.filter(item => item.useType ==='BY_GOODS_TYPE').map(item => parseInt(item.relationId));
            this.tempGoodsSelect = data.relationList.filter(item => item.useType ==='BY_GOODS').map(item => {
              return {
                goods_id: item.relationId,
                title: item.relationName,
                type: 1
              }
            })
            this.tempPackageSelect = data.relationList.filter(item => item.useType ==='BY_PACKAGE').map(item => {
              return {
                goods_id: item.relationId,
                title: item.relationName,
                type: 2
              }
            })
            this.tempGoodsSelectBlack = data.goodsBlackList
            this.tempPackageSelectBlack = data.packageBlackList
            if(this.userGroup.length) {
              this.formData['BY_USER_GROUP'] = true
            }
            if(this.tempUserLevels.length) {
              this.formData['BY_USER_TYPE'] = true
            }
            if(this.tempGoodsModel.length) {
              this.formData['BY_MODEL_TYPE'] = true
            }
            if(this.tempGoodsCategory.length) {
              this.formData['BY_GOODS_TYPE'] = true
            }
            if(this.tempGoodsSelect.length) {
              this.formData['BY_GOODS'] = true
            }
            if(this.tempPackageSelect.length) {
              this.formData['BY_PACKAGE'] = true
            }
            this.pageLoading = false;
          }).catch(err => {
            console.log(err);
            this.pageLoading = false;
          });
        }
      },
      changeType(){
        this.$set(this.formData, 'inpageValue', '')
        this.$set(this.formData, 'inpageName', '')
      },
      chooseJump(){
          if(this.formData.inpageType === 'GOODS'){
              let checkData = [{
                  id: this.formData.jumpId,
                  name: this.formData.goodsName
              }];
              this.checkGoods(checkData, 1).then(val => {
                  this.$set(this.formData, 'inpageValue', val[0].id)
                  this.$set(this.formData, 'inpageName', val[0].name)
              });
              return false;
          } else if(this.formData.inpageType === 'PACKAGE'){
              let checkData = [{
                  packageId: this.formData.jumpId,
                  name: this.formData.goodsName
              }];
              this.checkPackage(checkData, 1).then(val => {
                  this.$set(this.formData, 'inpageValue', val[0].packageId)
                  this.$set(this.formData, 'inpageName', val[0].name)
              });
              return false;
          } else if(this.formData.type === 5){
              let checkData = [{
                  id: this.formData.jumpId,
                  name: this.formData.goodsName
              }];
              this.checkActivity(checkData, 1).then(val => {
                  this.formData.jumpId = val[0].id;
                  this.formData.goodsName = val[0].name;
              });
              return false;
          }
      },
      chooseGoodsBlack(){
        let selected = this.tempGoodsSelectBlack.filter(item=>item.type===1).map(item => {
          return {
            goodsId: item.foreignUuid,
            name: item.foreignName,
            id: item.foreignKey,
            serialNo: !item.serialNo ? '' : item.serialNo
          }
        });
        this.goodsChoose({}, selected).then(val => {
          this.tempGoodsSelectBlack = this.tempGoodsSelectBlack.filter(item=>item.type===2).concat(val.map(item => {
            return {
              foreignUuid: item.goodsId,
              foreignKey: item.id,
              foreignName: item.name,
              serialNo: !item.serialNo ? '' : item.serialNo,
              type: 1,
              from_type: 1
            }
          }))
        });
      },
      chooseGoodsPackageBlack(){
        let selected = this.tempPackageSelectBlack.filter(item=>item.type===2).map(item => {
          return {
            packageId: item.foreignUuid,
            name: item.foreignName,
            id: item.foreignKey,
            serialNo: !item.serialNo ? '' : item.serialNo
          }
        });
        this.packageChoose({}, selected).then(val => {
          this.tempPackageSelectBlack = this.tempPackageSelectBlack.filter(item=>item.type===1).concat(val.map(item => {
            return {
              foreignUuid: item.packageId,
              foreignKey: item.id,
              foreignName: item.name,
              serialNo: !item.serialNo ? '' : item.serialNo,
              type: 2,
              from_type: 3
            }
          }))
        });
      },
      removeTempSelectBlack(item) {
        const _this = this
        this.$confirm(`确定要删除 ${item.foreignName} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _this.tempGoodsSelectBlack.splice(_this.tempGoodsSelectBlack.indexOf(item), 1)
        }).catch(err => {
          console.log(err);
        });
      },
      removeTempPackageSelectBlack(item) {
        const _this = this
        this.$confirm(`确定要删除 ${item.foreignName} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _this.tempPackageSelectBlack.splice(_this.tempPackageSelectBlack.indexOf(item), 1)
        }).catch(err => {
          console.log(err);
        });
      },
      chooseGoods(){
        let selected = this.tempGoodsSelect.filter(item=>item.type===1).map(item => {
          return {
            goodsId: item.goods_id,
            image: item.pic,
            name: item.title,
            subName: item.subtitle,
            marketValue: item.marketValue,
            price: item.price
          }
        });
        this.goodsChoose({}, selected).then(val => {
          this.tempGoodsSelect = this.tempGoodsSelect.filter(item=>item.type===2).concat(val.map(item => {
            return {
              goods_id: item.goodsId,
              pic: item.image,
              title: item.name,
              subtitle: item.subName,
              marketValue: item.marketValue,
              price: item.price,
              type: 1,
              from_type: 1
            }
          }))
          this.setGoodsSelect()
        });
      },
      chooseGoodsPackage(){
        let selected = this.tempPackageSelect.filter(item=>item.type===2).map(item => {
          return {
            packageId: item.goods_id,
            image: item.pic,
            name: item.title,
            subTitle: item.subtitle,
            marketValue: item.marketValue,
            price: item.price,
            type: item.pack_type
          }
        });
        this.packageChoose({}, selected).then(val => {
          this.tempPackageSelect = this.tempPackageSelect.filter(item=>item.type===1).concat(val.map(item => {
            return {
              goods_id: item.packageId,
              pic: item.image,
              title: item.name,
              subtitle: item.subTitle,
              marketValue: item.marketValue,
              price: item.price,
              pack_type: item.type,
              type: 2,
              from_type: 3
            }
          }))
          this.setPackageSelect()
        });
      },
      removeTempSelect(item) {
        let relationListNew = this.formData.relationList.filter(item => item.useType !=='BY_GOODS_TYPE')
        const _this = this
        this.$confirm(`确定要删除 ${item.title} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _this.tempGoodsSelect.splice(_this.tempGoodsSelect.indexOf(item), 1)
          _this.setGoodsSelect()
        }).catch(err => {
          console.log(err);
        });
      },
      removeTempPackageSelect(item) {
        let relationListNew = this.formData.relationList.filter(item => item.useType !=='BY_PACKAGE')
        const _this = this
        this.$confirm(`确定要删除 ${item.title} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _this.tempPackageSelect.splice(_this.tempPackageSelect.indexOf(item), 1)
          _this.setPackageSelect()
        }).catch(err => {
          console.log(err);
        });
      },
      fetchCategoryData(){
        this.request({
          url: '/bsnl-product/category/tree',
          method: 'get'
        }).then(({data}) => {
          this.goodsCategory = data ? data : [];
        }).catch(err => {
          this.goodsCategory = [];
        });
      },
      // 选中新人用户
      setUserGroup(value){
        if (!this.formData['BY_USER_GROUP']) {
          return
        }
        let relationListNew = this.formData.relationList.filter(item => item.useType !=='BY_USER_GROUP')
        this.userGroup.map(item => {
          relationListNew.push({
            couponActivityId: this.id,
            relationId: 'NewUser',
            relationName: '新人用户',
            useType: 'BY_USER_GROUP'
          })
        });
        this.formData.relationList = relationListNew;
        this.$refs.form.validateField('relationList')
      },
      setUserLevels(value){
        if (!this.formData['BY_USER_TYPE']) {
          return
        }
        let relationListNew = this.formData.relationList.filter(item => item.useType !=='BY_USER_TYPE')
        this.tempUserLevels.map(item => {
          relationListNew.push({
            couponActivityId: this.id,
            relationId: item,
            relationName: this.userLevels[item],
            useType: 'BY_USER_TYPE'
          })
        });
        this.formData.relationList = relationListNew;
        this.$refs.form.validateField('relationList')
      },
      setGoodsModel(value){
        if (!this.formData['BY_MODEL_TYPE']) {
          return
        }
        let relationListNew = this.formData.relationList.filter(item => item.useType !=='BY_MODEL_TYPE')
        this.tempGoodsModel.map(item => {
          relationListNew.push({
            couponActivityId: this.id,
            relationId: item,
            relationName: this.businessModel[item],
            useType: 'BY_MODEL_TYPE'
          })
        });
        this.formData.relationList = relationListNew;
        this.$refs.form.validateField('relationList')
      },
      setGoodsCategory(obj, checkedObj){
        let relationListNew = this.formData.relationList.filter(item => item.useType !=='BY_GOODS_TYPE')
        let setGoodsCategoryTemp = []
        checkedObj.checkedNodes.map(item => {
          relationListNew.push({
            couponActivityId: this.id,
            relationId: item.id,
            relationName: item.name,
            useType: 'BY_GOODS_TYPE'
          })
          setGoodsCategoryTemp.push({
            couponActivityId: this.id,
            relationId: item.id,
            relationName: item.name,
            useType: 'BY_GOODS_TYPE'
          })
        });
        this.setGoodsCategoryTemp = setGoodsCategoryTemp
        this.formData.relationList = relationListNew
        this.$refs.form.validateField('relationList')
      },
      setGoodsSelect(){
        let relationListNew = this.formData.relationList.filter(item => (item.useType !=='BY_GOODS' && item.useType !=='BY_GOODS_TYPE'))
        this.tempGoodsSelect.map(item => {
          relationListNew.push({
            couponActivityId: this.id,
            relationId: item.goods_id,
            relationName: item.title,
            useType: 'BY_GOODS'
          })
        });
        this.formData.relationList = relationListNew
        this.$refs.form.validateField('relationList')
      },
      setPackageSelect(){
        let relationListNew = this.formData.relationList.filter(item => (item.useType !=='BY_PACKAGE'))
        this.tempPackageSelect.map(item => {
          relationListNew.push({
            couponActivityId: this.id,
            relationId: item.goods_id,
            relationName: item.title,
            useType: 'BY_PACKAGE'
          })
        });
        this.formData.relationList = relationListNew;
        this.$refs.form.validateField('relationList')
      },
      changeValidate(){
        this.$refs.form.clearValidate()
      },
      save(){
        this.$refs.form.validate(valid => {
          if (this.formData.useType==='BY_CONDITION' && !this.formData.relationList.length) {
            this.$message({
              type: 'info',
              message: '请选择指定范围'
            });
            return
          }

          if (!valid) {
            return false
          }

          this.btnLoading = true;
          if(this.formData.receiveTimeRange.length){
            this.formData.receiveStartTime = this.formData.receiveTimeRange[0];
            this.formData.receiveStopTime = this.formData.receiveTimeRange[1];
          }
          if(this.formData.useTimeType === 'BY_BETWEEN' && this.formData.useTimeRange.length){
            this.formData.useStartTime = this.formData.useTimeRange[0];
            this.formData.useStopTime = this.formData.useTimeRange[1];
          } else {
            this.formData.useStartTime = '';
            this.formData.useStopTime = '';
          }
          this.formData.goodsBlackList = this.tempGoodsSelectBlack
          this.formData.packageBlackList = this.tempPackageSelectBlack
          this.request({
            url: this.id ? '/coupon/system/activity/update' : '/coupon/system/activity/create',
            method: 'post',
            data: this.formData
          }).then(() => {
            this.$message.success('保存成功');
            this.$router.push({name: 'activityCoupon'});
          }).catch(err => {
            console.error(err);
            this.btnLoading = false;
          });
        });
      }
    }
  }
</script>
<style lang="scss">
    @import "../../../styles/_mixin.scss";
    .block-header{
        color: #1ea0ff;
        font-size: 14px;
        padding: 12px 0;
        margin-bottom: 12px;
        background: #f7f7f7;

        &>div{
            padding: 0 12px;
            border-left: 2px solid #1ea0ff;
        }
    }

    .coupon-edit .el-form .el-textarea .el-textarea__inner{
        height: auto;
    }
    .adviceTxt{
        color: #8c939d
    }
    .use-type-block{
        @include flex;
        margin-left: 24px;
    }
</style>
